var winston = require('winston');
var path = require('path');
var fs = require('fs');

module.exports = function(pool, req, res, next){
	var eventId = req.params.eventId;
	var test = req.query.test;
	var timestamp = req.query.timestamp || 0;
	var config;
	if(eventId){
		var queryString = 'SELECT pr.print_id, ph.filename, pr.copies, pr.is_fullfilled, pr.timestamp FROM print_list pr LEFT JOIN photo_list ph ON pr.photo_id=ph.photo_id WHERE pr.event_id=' + eventId + ' AND pr.timestamp > ' + timestamp + ' ORDER BY pr.print_id LIMIT 500';
		pool.getConnection(function(err, connection){
			if(err){
				winston.error('DB connection error: ' + err);
				res.status(500).send('DB connection error: ' + err);
			}
			connection.query(queryString, function(err, rows){
				if(err){
					winston.error('DB query error: ' + err);
					res.status(500).send('DB query error: ' + err);
				}else{
					var pathToConfig = path.join(__dirname, '../events', eventId + '/config.json');
					if(fs.existsSync(pathToConfig)){
						config = fs.readFileSync(pathToConfig);
						config = JSON.parse(config);
					}

					rows.forEach(function(row){
						var filename = row.filename;
						if(config && config.genQrcode){
							row.filename = req.protocol + "://" + req.hostname + "/assets/" + eventId + "/" + filename.replace(/(\.jpe?g)$/, "_qr$1");
						}else{
							row.filename = req.protocol + "://" + req.hostname + "/assets/" + eventId + "/" + filename.replace(/(\.jpe?g)$/, "_c$1");
						} 
					});
					res.send(rows);
					var unfullfilled = rows.filter(function(row){ return row.is_fullfilled === 0; });
					if(unfullfilled.length > 0){
						unfullfilled.forEach(function(row){
							var updateString = 'UPDATE print_list SET is_fullfilled=1 WHERE print_id=' + row.print_id;
							connection.query(updateString, function(err){
								if(err){
									winston.error(err);
								}
							});
						});
					}
				
				}
				connection.release();
			});
		});
	}else{
		winston.error('ROUT error, can not get eventId');
		res.status(500).send('ROUT error, can not get eventId')
	}
	
}